import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import { getToken } from "@/utils/auth";

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

service.interceptors.request.use((config) => {
  if (store.state.user.token) {
    //如果有token
    config.headers.token = getToken();
  }
  return config;
});
service.interceptors.response.use(
  (response) => {
    const res = response.data;

    // 如果返回的不是20000表示登录失败
    if (res.code !== 20000 && res.code !== 200) {
      Message({
        message:
          (typeof res.data == "string" && res.data) || res.message || "Error",
        type: "登录或者请求失败",
        duration: 1 * 1000,
      });
      if (response.status === 401) {
        // to re-login
        MessageBox.confirm("token过期", {
          confirmButtonText: "重新登录",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          // 清空token信息,清空用户信息
          store.dispatch("user/resetToken").then(() => {
            location.reload(); //reload() 方法类似于你浏览器上的刷新页面按钮
          });
        });
      }
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      return res.data;
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default service;
